﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Net;
using System.Web;
using System.Windows.Forms;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Wagner.Utilities;

namespace Wagner.SharePoint.Utilities
{
	internal class ListJobs : OperationBase
	{
		internal ListJobs()
		{}

		internal override void Run()
		{
			// -o ListJobs -url http://localhost -pause -debug
			// -o ListJobs -url http://localhost -jobtitle "SPDev: Timer Job Tester" -pause -debug
			
			string url = ValidateParameter("url", true, null);
			
			RunNow(url);
		}
		
		private void RunNow(string url)
		{
			using (SPSite site = new SPSite(url))
			{
				SPWebApplication webApp = site.WebApplication;
				
				Console.WriteLine("Timer Job List:");
				Console.WriteLine("  Web App:  " + webApp.Name);
				Console.WriteLine();

				string title = (Args["jobtitle"] == null) ? "" : Args["jobtitle"];

				SortedList<string, SPJobDefinition> jobs = new SortedList<string, SPJobDefinition>();

				// Sort jobs by title
				foreach (SPJobDefinition job in webApp.JobDefinitions)
				{
					if (title.Length == 0)
						jobs.Add(job.Title, job);
					else
					{
						if (job.Title.Equals(title, StringComparison.InvariantCultureIgnoreCase))
							jobs.Add(job.Title, job);
					}
				}

				foreach (KeyValuePair<string, SPJobDefinition> item in jobs)
				{
					SPJobDefinition job = item.Value;

					Console.WriteLine();
					Console.WriteLine("Job Title:        " + job.Title);
					Console.WriteLine("    Name:         " + job.Name);
					Console.WriteLine("    Display Name: " + job.DisplayName);
					Console.WriteLine("    ID:           " + job.Id.ToString());
					Console.WriteLine("    Status:       " + job.Status.ToString());
					Console.WriteLine("    Disabled:     " + job.IsDisabled.ToString());
					Console.WriteLine("    LockType:     " + job.LockType.ToString());
					Console.WriteLine("    Retry:        " + job.Retry.ToString());
					Console.WriteLine("    Last Run:     " + job.LastRunTime.ToString());
					Console.WriteLine("    Schedule:     " + job.Schedule.ToString());
				}

				return;
			}
		}

		internal override string HelpSummary
		{
			get
			{
				return @"
-o ListJobs
     Lists the timer jobs for the specified web application along with some
     job definition details. Useful when trying to identify a job ID/GUID.";
			}
		}

		internal override string HelpDetail
		{
			get
			{
				string help = HelpSummary + @"
Usage:
  SPDev.exe -o ListJobs -url <url>
  
    Parameters:  
     -url <url>
       Specifies the url of the web application on the local machine.

     [-jobtitle <title>]
       Lists only the job having the specified job title.
       
Examples:
 SPDev.exe -o ListJobs -url http://localhost 

";

				return help;
			}
		}
	
	}
}
